
package vozovypark;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Andrej Hraško
 */
public class ReservationDAOImpl implements ReservationDAO{
    
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("VozovyPark_PU");
    
    public void create(Reservation reservation){
        if (reservation != null){
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            
            em.persist(reservation);
            
            em.getTransaction().commit();
            em.close();
        } throw new IllegalArgumentException("Argument is NULL");
    }
    
    public void update(Reservation reservation){
        if (reservation != null){
            Reservation temp = getByID(reservation.getId());
            
            if (temp == null){ return; }
            EntityManager em = emf.createEntityManager();
            
            em.getTransaction().begin();
            temp = reservation;
            em.persist(temp);
            
            em.getTransaction().commit();
            em.close();
        } throw new IllegalArgumentException("Argument is NULL");
    }
   
    public void remove(Reservation reservation){
        if (reservation != null){
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            
            Reservation temp = em.find(Reservation.class, reservation.getId());
            if (temp != null){
                em.remove(temp);
            }
            em.getTransaction().commit();
            em.close();
        }  throw new IllegalArgumentException("Argument is NULL");
    }
    
    public Reservation getByID(Long id) {
        EntityManager em = emf.createEntityManager();
        Reservation temp = em.find(Reservation.class, id);
        em.close();
        return temp;
    }
    
    public List<Reservation> get(Employee employee){
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        
        Query q = em.createQuery("SELECT r FROM Reservation r WHERE employee=" +employee); 
        List<Reservation> result = q.getResultList();
        
        em.getTransaction().commit();
        em.close();
        return result;
    }

    
}
